package com.sxj.PDMS.controller.student;


import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.sxj.PDMS.common.ErrorCode;
import com.sxj.PDMS.exception.BusinessException;
import io.swagger.annotations.ApiOperation;
import com.sxj.PDMS.common.BaseResponse;
import com.sxj.PDMS.common.Result;
import com.sxj.PDMS.model.dto.admin.DataInformationRequest;
import com.sxj.PDMS.model.vo.PagingQueryResponse;
import com.sxj.PDMS.model.entity.DataInformationList;
import com.sxj.PDMS.service.DataInformationListService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import javax.servlet.http.HttpServletResponse;
import java.io.OutputStream;
import java.net.URLEncoder;
import java.util.List;

@CrossOrigin
@RestController
@RequestMapping("/student/resource")
@Slf4j
public class StudentResourceController {
    @Autowired
    private DataInformationListService dataInformationListService;

    @GetMapping("/selectAll_resource")
    public BaseResponse<PagingQueryResponse<DataInformationList>> selectResource(@RequestParam(defaultValue = "1") Integer page,
                                                                                 @RequestParam(defaultValue = "10") Integer pageSize) {
        log.info("分页查询 ：page:{}, pageSize:{}", page, pageSize);
        PagingQueryResponse<DataInformationList> pagingQueryResponse = dataInformationListService.selectAll(page, pageSize);
        return Result.success(pagingQueryResponse);

    }

    @GetMapping("/select_resource")
    public BaseResponse<PagingQueryResponse<DataInformationList>> selectWithCondition(@RequestParam(defaultValue = "1") Integer page,
                                                                                      @RequestParam(defaultValue = "10") Integer pageSize,
                                                                                      DataInformationRequest dataInformationRequest) {

        PagingQueryResponse<DataInformationList> pagingQueryResponse = dataInformationListService.dataInformationListSelect(page, pageSize, dataInformationRequest);

        return Result.success(pagingQueryResponse);
    }

    // todo 资料文件下载
//    @ApiOperation(value = "downloadResource", produces = "application/octet-stream")
//    @GetMapping("/download_resource")
//    public void downloadResource(HttpServletResponse response,
//                                 @RequestParam("dataContent") String downloadFile) throws Exception {
//        log.info("下载文件：{}", downloadFile);
//
//        QueryWrapper<DataInformationList> queryWrapper = new QueryWrapper<>();
//        queryWrapper.eq("data_content", downloadFile);
//        DataInformationList dataInformationList = dataInformationListService.getOne(queryWrapper);
//        if (dataInformationList == null) {
//            throw new BusinessException(ErrorCode.PARAMS_ERROR, "库中没有该文件");
//        }
//        log.info("下载文件：{}", downloadFile);
//        //todo://resource存放位置
//        String path = "D:\\user\\Desktop\\store\\resource\\";
//        OutputStream outPutStream;
//        List<String> fileNames = FileUtil.listFileNames(path);
//        String avatar = fileNames.stream().filter(name -> name.contains(downloadFile)).findAny().orElse("");
//        try {
//            if (StrUtil.isNotEmpty(avatar)) {
//                response.addHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(avatar, "UTF-8"));
//                response.setContentType("application/octet-stream");
//                byte[] bytes = FileUtil.readBytes(path + "\\" + avatar);
//                outPutStream = response.getOutputStream();
//                outPutStream.write(bytes);
//                outPutStream.flush();
//                outPutStream.close();
//            }
//        } catch (Exception e) {
//            System.out.println(avatar + "下载失败");
//        }
//    }
    @ApiOperation(value = "downloadResource", produces = "application/octet-stream")
    @GetMapping("/download_resource")
    public void downloadResource(HttpServletResponse response,
                                 @RequestParam("dataContent") String downloadFile) throws Exception {
        log.info("下载文件：{}", downloadFile);

        QueryWrapper<DataInformationList> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("data_content", downloadFile);
        DataInformationList dataInformationList = dataInformationListService.getOne(queryWrapper);
        if (dataInformationList == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "库中没有该文件");
        }
        log.info("下载文件：{}", downloadFile);
        // TODO: resource存放位置
        String path = "D:\\user\\Desktop\\store\\resource\\";
        OutputStream outPutStream;
        List<String> fileNames = FileUtil.listFileNames(path);
        String avatar = fileNames.stream().filter(name -> name.contains(downloadFile)).findAny().orElse("");
        try {
            if (StrUtil.isNotEmpty(avatar)) {
                response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
                response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(avatar, "UTF-8"));
                byte[] bytes = FileUtil.readBytes(path + "\\" + avatar);
                outPutStream = response.getOutputStream();
                outPutStream.write(bytes);
                outPutStream.flush();
                outPutStream.close();
            }
        } catch (Exception e) {
            System.out.println(avatar + "下载失败");
        }
    }

}
